const express = require("express");
const cors = require("cors");
const app = express();
const jwt = require("jsonwebtoken");
const port = 3000;

const users = {
  username: "axie",
  password: "xiequantai1996",
};
app.use(express.json());
const OSS = require("ali-oss");
const { v4: uuidv4 } = require("uuid");
/**
 * 处理跨域问题
 */
app.use(
  cors({
    origin: "*", // 允许访问的来源
    methods: ["GET", "POST", "PUT", "DELETE"], // 允许的方法
    allowedHeaders: ["Content-Type", "Authorization", "tenant-id"], // 允许的请求头
  })
);

/**
 * 阿里云OSS配置：target-management
 */
const client2 = new OSS({
  accessKeyId: "LTAI5tQzisdhBJCrXFomdfCs",
  accessKeySecret: "meVd663LWSVf80fTrXSM1U5XnqLNdF",
  region: "oss-cn-guangzhou",
  bucket: "target-management",
});

/**
 * 配置multer中间件
 */
const multer = require("multer");
const storage = multer.memoryStorage();
const upload = multer({ storage });

/**
 * 对本地文件改名字,使用uuid生成新的名字（暂时不需要）
 */
function generateFileName(fileName) {
  // 处理空文件名的情况
  if (!fileName) return uuidv4();

  const lastDotIndex = fileName.lastIndexOf('.');
  
  // 没有点号：直接返回UUID
  if (lastDotIndex === -1) return uuidv4();
  
  // 有点号但位于首字符（如 ".gitignore"）
  if (lastDotIndex === 0) return uuidv4() + fileName;
  
  // 标准情况：提取扩展名并拼接UUID
  const fileExt = fileName.substring(lastDotIndex);
  return uuidv4() + fileExt;
}
const verifyToken = (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).send("未提供 token");
  }
  const token = authHeader.split(" ")[1];
  jwt.verify(token, "04086999-3c6b-4183-9b46-5d36c13f7e7a", (err, user) => {
    if (err) {
      return res.status(403).send("无效的 token");
    }
    req.user = user;
    next();
  });
};
/**
 * 配置路由
 */
app.post("/upload/login", (req, res) => {
  const { username, password } = req.body;
  if (username === users.username && password === users.password) {
    // 生成token
    const token = jwt.sign(
      { username },
      "04086999-3c6b-4183-9b46-5d36c13f7e7a",
      { expiresIn: "30m" }
    );
    res.json({ token });
  } else {
    res.status(401).json({ message: "Invalid credentials" });
  }
});

app.get("/getFolders",verifyToken,async(req,res)=>{
  try {
    // 获取文件夹列表，设置 delimiter 为 '/'
    const result = await client2.list({
      prefix: '',  // 空字符串表示列举所有对象
      delimiter: '/',  // 以 '/' 作为分隔符
    });

    // 输出所有文件夹前缀
    res.send({
      status:200,
      msg:'success',
      data:result.prefixes
    })
  } catch (err) {
    console.error('Error listing folders:', err);
  }
})

app.post(
  "/uploadFile",
  upload.single("file"),
  verifyToken,
  async (req, res) => {
    try {
      const file = req.file;
      const folder = req.body.folder || '/';
      const fullPath = `${folder}${generateFileName(req.file.originalname)}`
      const result = await client2.put(
        fullPath,
        file.buffer
      );
      res.send({
        status: 200,
        msg: "上传成功",
        url: result.url,
      });
    } catch (error) {
      console.error(error);
      res.send("文件上传失败");
    }
  }
);

app.listen(port, () => {
  console.log(`运行: http://localhost:3000/uploadFile`);
});
